package com.weblog.user.controller;

import com.weblog.model.user.Permission;
import com.weblog.user.service.PermissionService;
import entity.Result;
import entity.ResultMessage;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author MaoLin Wang
 * @date 2019/9/1818:00
 */
@RestController
@CrossOrigin
@RequestMapping("/permissions")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private HttpServletRequest request;

    /**
     * 查询权限列表
     *
     * @return
     */
    @GetMapping
    public Result PermissionList() {
        return new Result(true, StatusCode.OK, ResultMessage.QUERY_SUCCESS, permissionService.permissionList());
    }

    /**
     * 添加权限
     *
     * @param permission
     * @return
     */
    @PostMapping
    public Result addRole(@RequestBody Permission permission) {
        boolean flag = permissionService.addPermission(permission);
        if (flag) {
            return new Result(true, StatusCode.OK, ResultMessage.SAVE_SUCCESS);
        }
        return new Result(false, StatusCode.ACCESSERROR, ResultMessage.ACCESS_ERROR);
    }


    /**
     * 根据id查询权限信息
     *
     * @param pid
     * @return
     */
    @GetMapping("/{pid}")
    public Result getById(@PathVariable("pid") String pid) {
        return new Result(true, StatusCode.OK, ResultMessage.QUERY_SUCCESS, permissionService.getById(pid));
    }

    /**
     * 修改信息
     *
     * @param permission
     * @return
     */
    @PutMapping
    public Result update(@RequestBody Permission permission) {
        String token = (String) request.getAttribute("claims_superAadmin");
        if (token != null && !"".equals(token)) {
            permissionService.update(permission);
            return new Result(true, StatusCode.OK, ResultMessage.UPDATE_SUCCESS);
        }
        return new Result(false, StatusCode.ACCESSERROR, ResultMessage.ACCESS_ERROR);

    }

    /**
     * 删除权限
     *
     * @param pid
     * @return
     */
    @DeleteMapping("/{pid}")
    public Result delete(@PathVariable("pid") String pid) {
        String token = (String) request.getAttribute("claims_superAadmin");
        if (token != null && !"".equals(token)) {
            int flag = permissionService.delete(pid);
            if (flag == 1) {
                return new Result(true, StatusCode.OK, ResultMessage.DELETE_SUCCESS);
            }
            //目标权限已不存在
            return new Result(false, StatusCode.ERROR, ResultMessage.PERMISSION_NOT_FOUND);
        }
        //权限不足
        return new Result(false, StatusCode.ACCESSERROR, ResultMessage.ACCESS_ERROR);

    }


}
